package com.quick.proxy.client;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import com.quick.proxy.client.handler.real.RealProxyChildChannelHandler;
import com.quick.proxy.core.*;
import com.quick.proxy.core.utils.ByteUtils;
import com.quick.proxy.core.utils.LockUtils;
import com.quick.proxy.core.utils.ProxyUtils;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;


/**
 * Description:  代理客户端连接真实代理客户端
 * Author: 吃素不吃肉
 * Date: 2023/7/3
 *
 * @author 吃素不吃肉
 */
@Match(CmdTypeConstants.CONNECT)
@Component
@Slf4j
public class ProxyMessageConnectHandler implements ProxyMessageHandler {
    @Autowired
    private RealProxyChildChannelHandler realProxyChildChannelHandler;

    /**
     * 接收的数据帧包
     *
     * @param ctx          上下文
     * @param proxyMessage 帧报文
     */
    @Override
    public void cmdResponse(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
        String data = ByteUtils.hexToString(proxyMessage.getData());
        ForwardMessage forwardMessage = JSONUtil.toBean(data, ForwardMessage.class);
        String visitorId = forwardMessage.getVisitorId();
        String realProxyClientAddress = new String(forwardMessage.getBytes(), StandardCharsets.UTF_8);
        log.info("visitorId[{}]连接真实代理客户端:{}", visitorId, realProxyClientAddress);
        LockUtils.VISITOR_LOCK.put(visitorId, new LockUtils.VisitorLock());
        //获取真实代理客户端通道
        String[] realProxyClientAddressArr = new String(forwardMessage.getBytes(), StandardCharsets.UTF_8).split(":");
        ProxyUtils.Address address = ProxyUtils.Address.create(realProxyClientAddressArr);
        ChannelConstants.VISITOR_ID_PROXY_CHANNEL.put(visitorId, ctx.channel());
        ThreadUtil.execute(() -> ProxyUtils.createRealProxyClient(address.getIp(), address.getPort(), visitorId, realProxyChildChannelHandler));

    }
}
